package com.tianpengcc.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.tianpengcc.model.DateType;
import com.tianpengcc.model.User;
import com.tianpengcc.model.custom.DirayTypeCustom;
import com.tianpengcc.service.DirayService;
import com.tianpengcc.service.DirayTypeService;
import com.tianpengcc.service.UserService;
import com.tianpengcc.service.impl.DirayServiceImpl;
import com.tianpengcc.service.impl.DirayTypeServiceImpl;
import com.tianpengcc.service.impl.UserServiceImpl;
import com.tianpengcc.util.PropertiesUtil;

public class UserServlet extends HttpServlet {

	private DirayService dirayService = new DirayServiceImpl();

	private DirayTypeService dirayTypeService = new DirayTypeServiceImpl();

	private UserService userService = new UserServiceImpl();

	/**
	 * <p>
	 * Description:
	 * </p>
	 * <p>
	 * Compary
	 * </p>
	 * 
	 * @author 田鹏
	 * @date 2017年10月27日下午8:28:24
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String method = request.getParameter("method");
			String resultPath = "";
			if ("editUI".equals(method)) {
				resultPath = editUI(request, response);
			} else if ("edit".equals(method)) {
				resultPath = edit(request, response);
			}

			List<DirayTypeCustom> dirayTypeList = dirayTypeService.getAll();
			List<DateType> dateTypeList = dirayService
					.getDateTypeBySize(Integer.parseInt(PropertiesUtil
							.getValue("dateTypeSize")));

			String[] actionMethod = resultPath.split(":");
			if ("dispatcher".equals(actionMethod[0])) {
				request.setAttribute("mainPage", actionMethod[1]);
				request.setAttribute("dateTypeList", dateTypeList);
				request.setAttribute("dirayTypeList", dirayTypeList);
				request.getRequestDispatcher("/main.jsp").forward(request,
						response);
			} else {
				response.sendRedirect(request.getContextPath()
						+ actionMethod[1]);
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", "多半是错误了！");
			request.getRequestDispatcher("/error.jsp").forward(request,
					response);
		}
	}

	public String editUI(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return "dispatcher:/user/userEdit.jsp";
	}

	public String edit(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		String path = request.getSession().getServletContext()
				.getRealPath(PropertiesUtil.getValue("userImagePath"));
		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024 * 1024);// 设置创建缓冲大小
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(-1);// 设置上传文件限制大小,-1无上限

		try {
			@SuppressWarnings("unchecked")
			List<FileItem> list = upload.parseRequest(request);
			String nickName = "";
			String mood = "";
			String userId = "";
			String imagePath = "";
			for (FileItem item : list) {
				// String name = item.getFieldName();
				if (item.isFormField()) {// 判断是否是文件流

					String fieldName = item.getFieldName();
					System.out.println(fieldName);
					if ("nickName".equals(fieldName)) {
						nickName = item.getString("UTF-8");
					} else if ("mood".equals(fieldName)) {
						mood = item.getString("UTF-8");
					} else if ("userId".equals(fieldName)) {
						userId = item.getString("UTF-8");
					}
					// System.out.println(name+"="+va);
					// / request.setAttribute(name, value);
				} else {
					String value = item.getName();// 会将完整路径名传过来
					if (value == null || "".equals(value)) { // 没有给对象
						User user = userService.findByIdAndNotPath(Integer
								.parseInt(userId));
						imagePath = user.getImagePath();
					} else {
						int start = value.lastIndexOf("\\");
						String fileName = value.substring(start + 1);
						int index = fileName.lastIndexOf("."); // 寻找最后点的位置
						String realFileName = fileName.substring(0, index); // 真实文件名
						String subfix = fileName.substring(index);
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyyMMddHHmmss");
						realFileName = sdf.format(new Date()); // 返回文件的真实文件名
						fileName = realFileName + subfix;
						imagePath = fileName;

						InputStream in = item.getInputStream();
						System.out.println(path);
						System.out.println(fileName);
						File file = new File(path + File.separator + fileName);
						OutputStream out = new FileOutputStream(file);
						byte[] data = new byte[1024];
						int temp = 0;
						while ((temp = in.read(data)) != -1) {
							out.write(data, 0, temp);
						}
						out.close();
						in.close();
					}
				}
			}
			User user = new User();
			user.setUserId(Integer.parseInt(userId));
			user.setNickName(nickName);
			user.setMood(mood);
			user.setImagePath(imagePath);
			userService.doUpdate(user.getUserId(), user);
			User newUser = userService.findById(user.getUserId());
			User oldUser = (User) request.getSession().getAttribute("user");
			oldUser.setImagePath(newUser.getImagePath());
			oldUser.setNickName(newUser.getNickName());
			oldUser.setMood(newUser.getMood());
			
		} catch (Exception e) {

			e.printStackTrace();
		}
		return "sendRedirect:/main";
	}
}
